package com.example.demo.xss;

import com.example.demo.utils.common.StringUtils;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.DispatcherType;
import java.util.HashMap;
import java.util.Map;

/**
 * XSS拦截器配置
 */
@Configuration
public class XssFilterConfig {

    /** 基础配置，建议放到配置文件中，此处为了方便理解，直接声明 */
    /** 启用开关 */
    private String enabled = "true";
    /** 排除路径，多个用逗号分隔 */
    private String excludes = "/xss/test/no/filter";
    /** 匹配连接，多个用逗号分隔 */
    private String urlPatterns = "/*";

    @Bean
    public FilterRegistrationBean xssFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        /** 设置XSS拦截器 */
        registration.setFilter(new XssFilter());
        /** 设置匹配路径 */
        registration.addUrlPatterns(StringUtils.split(urlPatterns, ","));
        registration.setName("xssFilter");
        registration.setOrder(Integer.MAX_VALUE);
        /** 排除路径及开启参数 */
        Map<String, String> initParameters = new HashMap<String, String>();
        initParameters.put("excludes", excludes);
        initParameters.put("enabled", enabled);
        registration.setInitParameters(initParameters);
        return registration;
    }

}
